/*
* 资源管理
*/
import React from 'react';
import BreadcrumbCustom from '../BreadcrumbCustom';
import { Row,Button,Modal,Input,message,Form } from 'antd';
import qs from 'qs';
import * as Request from '../../Server/SystemManger';
import {AuthA,AuthButton} from '../auth/OperationAuth';
import TablePage from "../TablePage";
import * as Constant from '../../common/const';
require('./customer.css');

const confirm = Modal.confirm;
const defaultPage = {page:Constant.DEFAULT_PAGE,size:Constant.DEFAULT_PAGE_SIZE};
const FormItem = Form.Item;

class RoleManager extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            name:null,
            role:{},
            disable:false,
            data : [],
            pagination:{},
            loading:true,
            searchKey:null,
            default:{}
        };
    }
    componentDidMount() {
        const state = this.props.location.state;
        if(state && Object.keys(state).length){
            const {current,pageSize} = state;
            const params = {page:current-1,size:pageSize};
            state.name && (params.name = state.name);
            this.setState({searchKey:state.name});
            this.fetch(params);
        }else{
            this.fetch();
        }
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }

    fetch = (params = defaultPage) => {
        this.setState({loading:true});
        const _this = this;
        let paramStr = qs.stringify(params);
        Request.getRolePage(paramStr).then(function(res){
            if(res && Constant.REQUEST_SUCCESS == res.code){
                let data = res.data;
                _this.setState({
                    data:data.content,
                    pagination:{..._this.state.pagination,total:data.totalSize,current:data.page + 1,pageSize:params.size},
                    loading:false,
                });
            }
        })
    }
    /* 翻页 */
    handleTableChange = (pagination) => {
        const _this = this;
        const pager = { ..._this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        _this.setState({
            pagination: pager,
            loading:true
        });
        _this.fetch({
            page: pagination.current -1 ,//后台分页默认从第0页开始
            size: pagination.pageSize,
            name:_this.state.searchKey
        });
    }
    /*
    *添加
    */
    addRole = () => {
        this.props.history.push({
            pathname:'/app/system/roles/add',
            state:{...this.state.pagination,name:this.state.searchKey}
        });
    }
    /*查看*/
    detail = (id) =>{
        this.props.history.push({
            pathname:'/app/system/roles/detail/'+ id,
            state:{...this.state.pagination,name:this.state.searchKey}
        });
    }
    /*编辑*/
    edit = (id) => {
        this.props.history.push({
            pathname:'/app/system/roles/edit/' + id,
            state:{...this.state.pagination,name:this.state.searchKey}
        });
    }
    showConfirm = (id,row) => {
        if(row.id == 1){
            message.error('超级管理员不允许删除!',Constant.AUTO_DISAPPEAR_TIME);
            return;
        }
        confirm({
            title: '删除提示',
            content: '确认删除该条信息',
            maskClosable: true,
            okText: '确定',
            okType:'primary',
            cancelText: '取消',
            onOk:this.delete.bind(this,id)
        });
    }
    /*删除*/
    delete = (id) =>{
        /* do something */
        Request.deleteRoleById(id).then(res => {
            if(res && Constant.REQUEST_SUCCESS == res.code){
                message.success('删除成功!', Constant.AUTO_DISAPPEAR_TIME);
                this.fetch(this.getPageParams(true));
            }
        });
    }

    getPageParams = (isDelete = false,pagination = this.state.pagination) => {
        const params = {
            page: pagination.current -1 ,//后台分页默认从第0页开始
            size: pagination.pageSize || Constant.DEFAULT_PAGE_SIZE,
            name:this.state.searchKey
        };
        if(isDelete && pagination.current == Math.ceil(pagination.total/pagination.pageSize)
            && pagination.total%pagination.pageSize == 1){
            params.page > 0 && params.page --;
        }
        return params;
    }

    search = () => {
        const name = this.props.form.getFieldValue('name');
        this.setState({
            searchKey: name
        });
        this.fetch({page:Constant.DEFAULT_PAGE,size:this.currentPageSize(),name:name});
    }
    reset = () => {
        this.setState({
            searchKey: undefined
        });
        this.props.form.setFieldsValue({name:undefined});
        this.fetch({page:Constant.DEFAULT_PAGE,size:this.currentPageSize()});
    }

    currentPageSize = () => this.state.pagination.pageSize || Constant.DEFAULT_PAGE_SIZE;

    render(){
        const { getFieldDecorator } = this.props.form;
        const columns = [
            {
                title:"ID",
                dataIndex:"id",
                width:'33.33%',
                align:'center',
            },
            {
                title:"角色名称",
                dataIndex:"name",
                width:'33.33%',
                align:'center',
            },
            {
                title:"权限操作",
                width:'33.33%',
                align:'center',
                render:(text, record) =>
                    (
                        <span>
                             <AuthA onClick={this.detail.bind(this,record.id)} className={'operation-primary'} permission={'role:get'}>查看</AuthA>
                             <AuthA disabled={record.id==1} onClick={this.edit.bind(this,record.id)} className={'operation-primary'} permission={'role:save'}>编辑</AuthA>
                             <AuthA disabled={record.id==1} onClick={this.showConfirm.bind(this,record.id,record)} className={'operation-danger'} permission={'role:delete'}>删除</AuthA>
                         </span>
                    )
            }
        ];
        return (
            <div>
                <BreadcrumbCustom  first={"角色管理"}/>
                <Row>
                    <Form  layout="inline" onSubmit={this.search}>
                        <FormItem  label={'角色名称:'}>
                            {getFieldDecorator('name',{
                                initialValue:this.props.location.state && this.props.location.state.name,
                            })(
                                <Input maxLength={255}/>
                            )}
                        </FormItem>
                        <FormItem >
                            <Button
                                type="primary"
                                htmlType="submit"
                            >查询</Button>
                            <Button
                                type="default"
                                onClick={this.reset}
                            >重置</Button>
                        </FormItem>
                    </Form>
                </Row>
                <Row span={2} className="button-margin" >
                    <AuthButton  size={'large'} onClick={this.addRole} permission={'role:save'}>
                        新增角色
                    </AuthButton>
                </Row>
                <TablePage
                    dataSource={this.state.data}
                    columns={columns}
                    rowKey={record => record.id}
                    pagination={this.state.pagination}
                    loading={this.state.loading}
                    onChange={this.handleTableChange}
                />
            </div>
        )
    }
}

const RoleManagers = Form.create()(RoleManager);
export default RoleManagers;